﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KL.Store.Web.Models;
using KL.Store.Data;
using KL.Store.Core;
using KL.Store.Core.Domain;
using KL.Store.Core.POS;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using System.Globalization;

namespace KL.Store.Web.Controllers
{
    public class ProductController : KL.Store.Core.Web.BaseController
    {
        #region Index

        public ActionResult Index(int? id, string goNewUrl = "")
        {
            if (id.HasValue)
            {
                ProductMeta pm = dbProduct.GetMeta((int)id);
                Product pd = dbProduct.Get((int)id, eStoreUser.AccountId);
                if (pm != null && pd != null)
                {
                    if (!string.IsNullOrEmpty(goNewUrl) && pd.LinkUrl.Contains(goNewUrl))
                    {
                        return RedirectPermanent(pd.LinkUrl);
                    }
                    /*fiyat hesaplama*/
                    var fiyat = pd.PriceWithTax.ToString("###,###,##0.00") + " " + pd.Currency;
                    if (pd.CreditCardPrice > 0 && pd.CreditCardPrice != pd.PriceWithTax)
                    {
                        fiyat = pd.CreditCardPrice.ToString("###,###,##0.00") + " " + pd.Currency;
                    }
                    /*fiyat hesaplama*/

                    ViewBag.Title = string.IsNullOrEmpty(pm.WebTitle) ? pm.ProductName : pm.WebTitle;
                    ViewBag.Keywords = string.IsNullOrEmpty(pm.Keywords) ? pm.ProductName.Replace(" ", ", ") : pm.Keywords;
                    ViewBag.Description = string.IsNullOrEmpty(pm.Description) ? pm.ProductName : pm.ProductName + "; " + pm.Description;
                    if (!string.IsNullOrEmpty(fiyat))
                    {
                        ViewBag.Description += " Fiyatı " + fiyat;
                    }
                    ViewBag.FacebookSharingImage = Parameters.WebSiteImageUrl + "/product-large/" + pm.ProductId + "_1.jpg";
                    var websiteUrl = dbRefs.GetRef1(1913) == "E" ? Parameters.WebSiteUrl.Replace("http://", "https://") : Parameters.WebSiteUrl;
                    ViewBag.CanonicalUrl = !string.IsNullOrEmpty(pd.CanonicalLink) ? websiteUrl + "/urun" + pd.CanonicalLink + "-" + pm.ProductId + ".html" : websiteUrl + pd.LinkUrl;
                    if (!string.IsNullOrEmpty(Parameters.InstallmentInfo))
                    {
                        ViewBag.Description += ", " + Parameters.InstallmentInfo;
                    }
                    eStoreUser.RedirectUrl = pd.LinkUrl;
                }
                else
                {
                    return Redirect("/Content/404");
                }
            }
            return View();
        }

        #endregion

        #region Print

        public ActionResult Print(int? id)
        {
            if (id.HasValue)
            {
                ProductMeta pm = dbProduct.GetMeta((int)id);
                Product pd = dbProduct.Get((int)id, eStoreUser.AccountId);
                if (pm != null)
                {
                    ViewBag.Title = pm.ProductName;
                    ViewBag.Keywords = string.IsNullOrEmpty(pm.Keywords) ? Parameters.WebSiteTitle + " " + pm.ProductName : pm.Keywords;
                    ViewBag.Description = string.IsNullOrEmpty(pm.Description) ? Parameters.WebSiteTitle + " " + pm.ProductName : pm.Description;
                    var websiteUrl = dbRefs.GetRef1(1913) == "E" ? Parameters.WebSiteUrl.Replace("http://", "https://") : Parameters.WebSiteUrl;
                    ViewBag.CanonicalUrl = !string.IsNullOrEmpty(pd.CanonicalLink) ? websiteUrl + "/urun" + pd.CanonicalLink + "-" + pm.ProductId + ".html" : websiteUrl + pd.LinkUrl;
                }
                else
                {
                    return Redirect("/Content/404");
                }
            }
            else
            {
                return Redirect("/Content/404");
            }
            return View();
        }

        #endregion

        #region Get

        [Child]
        public ActionResult Get(int? id, int? CategoryId, string Ref)
        {
            var cacheKey = "ProductGet" + id + CategoryId + Ref;
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                if (!string.IsNullOrEmpty(Ref))
                {
                    eStoreUser.UTMReferral = Ref.ToUpperInvariant();
                    Session["eStoreUser"] = eStoreUser;
                }
                return PartialView(HttpRuntime.Cache[cacheKey] as KL.Store.Web.Models.ProductModel);
            }

            ProductModel productModel = new ProductModel();
            productModel.BreadCrumb = "";

            if (id.HasValue)
            {
                Product p = dbProduct.Get((int)id, eStoreUser.AccountId);
                if (p != null)
                {
                    Mapper.MapDomainToViewModel(p, productModel);
                    productModel.Information = dbProductInfo.GetListHtml((int)id).Replace("|||", ", ");

                    //var cacheManager = CacheFactory.GetCacheManager("Cache Manager");
                    //productModel.PosList = (List<Pos>)cacheManager.GetData("PosList");

                    productModel.PosList = Parameters.PosList;
                    productModel.ProductImages = dbProduct.GetImageList((int)id);
                    productModel.variantPropertiesList = dbProduct.GetVariantCombo((int)id);
                    productModel.variantUrlsList = dbProduct.GetVariantUrls((int)id);
                    productModel.Group = dbCategory.Get(productModel.CategoryId);
                    productModel.LinkedProducts = dbProduct.GetLinkedProducts((int)id);
                    if (string.IsNullOrEmpty(productModel.Description))
                    {
                        productModel.Description = dbProduct.GetDescription((int)id);
                    }
                    productModel.Description = productModel.Description.Replace("{ImageUrl}", Parameters.WebSiteImageUrl).Replace("\r", "").Replace("\n", "").Replace("\t", "");

                    if (productModel.CategoryId > 0)
                    {
                        productModel.BreadCrumb = dbCategory.GetBreadCrumb(productModel.CategoryId, Parameters.MainCategoryId, Parameters.HomePageCategoryId, eStoreUser.CultureInfo);

                        productModel.ProductTabsWithNewTab = Parameters.ProductTabsWithNewTab.Where(t => t.IdGrup == productModel.CategoryId).ToList<ProductTab>();
                        productModel.ProductTabsWithoutNewTab = Parameters.ProductTabsWithoutNewTab.Where(t => t.IdGrup == productModel.CategoryId).ToList<ProductTab>();
                    }

                    #region UTM Referral to Session

                    if (!string.IsNullOrEmpty(Ref))
                    {
                        eStoreUser.UTMReferral = Ref.ToUpperInvariant();
                        Session["eStoreUser"] = eStoreUser;
                    }

                    #endregion

                }
            }
            productModel.IsManager = eStoreUser.IsManager;
            productModel.IsSeoManager = eStoreUser.IsSeoManager;
            productModel.BasketLocked = eStoreUser.BasketLocked;

            if (productModel.ProductTabsWithNewTab == null) { productModel.ProductTabsWithNewTab = new List<ProductTab>(); }
            if (productModel.ProductTabsWithoutNewTab == null) { productModel.ProductTabsWithoutNewTab = new List<ProductTab>(); }

            if (string.IsNullOrEmpty(productModel.BreadCrumb) && CategoryId.HasValue && CategoryId > 0)
            {
                productModel.BreadCrumb = dbCategory.GetBreadCrumb((int)CategoryId, Parameters.MainCategoryId, Parameters.HomePageCategoryId, eStoreUser.CultureInfo);
            }
            if (productModel.Description == null)
            {
                productModel.Description = "";
            }
            HttpRuntime.Cache.Add(cacheKey, productModel, null, DateTime.UtcNow.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);
            return PartialView(productModel);
        }

        #endregion

        #region GetRelatedProducts
        //[Child]
        //public ActionResult GetRelatedProducts(int? id, int? CategoryId, string Ref)
        //{
        //    ProductModel productModel = new ProductModel();
        //    if(id.HasValue){

        //    }
        //    productsModel.RelatedProducts = dbProduct.GetList((int)id, 0, (int)brand, eStoreUser.AccountId, "").OrderBy(o => o.RewardPoints).ToArray<Product>();

        //    return PartialView(relatedProductsModel);
        //}
        #endregion

        #region GetPrint

        [Child]
        public ActionResult GetPrint(int? id, int? CategoryId)
        {
            return Get(id, CategoryId, "");
        }

        #endregion

        #region Basic

        #region BasicIndex

        public ActionResult BasicIndex(int? id)
        {
            if (id.HasValue)
            {
                ProductMeta pm = dbProduct.GetMeta((int)id);
                if (pm != null)
                {
                    ViewBag.Title = pm.ProductName;
                    ViewBag.Keywords = string.IsNullOrEmpty(pm.Keywords) ? pm.ProductName : pm.Keywords;
                    ViewBag.Description = string.IsNullOrEmpty(pm.Description) ? pm.ProductName : pm.ProductName + "; " + pm.Description;
                }
            }
            return View();
        }

        #endregion

        #region BasicGet

        [Child]
        public ActionResult BasicGet(int? id, int? CategoryId, string Ref)
        {
            ProductModel productModel = new ProductModel();
            productModel.BreadCrumb = "";

            if (id.HasValue)
            {
                Product p = dbProduct.Get((int)id, eStoreUser.AccountId);
                if (p != null)
                {
                    Mapper.MapDomainToViewModel(p, productModel);
                    productModel.Information = dbProductInfo.GetListHtml((int)id);

                    //var cacheManager = CacheFactory.GetCacheManager("Cache Manager");
                    //productModel.PosList = (List<Pos>)cacheManager.GetData("PosList");

                    productModel.PosList = Parameters.PosList;
                    productModel.ProductImages = dbProduct.GetImageList((int)id);
                    productModel.variantPropertiesList = dbProduct.GetVariantCombo((int)id);

                    if (productModel.CategoryId > 0)
                    {
                        productModel.BreadCrumb = dbCategory.GetBreadCrumb(productModel.CategoryId, Parameters.MainCategoryId, Parameters.HomePageCategoryId, eStoreUser.CultureInfo);

                        productModel.ProductTabsWithNewTab = Parameters.ProductTabsWithNewTab.Where(t => t.IdGrup == productModel.CategoryId).ToList<ProductTab>();
                        productModel.ProductTabsWithoutNewTab = Parameters.ProductTabsWithoutNewTab.Where(t => t.IdGrup == productModel.CategoryId).ToList<ProductTab>();
                    }

                    #region UTM Referral to Session

                    if (!string.IsNullOrEmpty(Ref))
                    {
                        eStoreUser.UTMReferral = Ref.ToUpperInvariant();
                        Session["eStoreUser"] = eStoreUser;
                    }

                    #endregion

                    //ProductMeta pm = dbProduct.GetMeta((int)id);
                    //if (pm != null)
                    //{
                    //    ViewBag.Title = pm.ProductName;
                    //    ViewBag.Keywords = string.IsNullOrEmpty(pm.Keywords) ? pm.ProductName : pm.Keywords;
                    //    ViewBag.Description = pm.ProductName + " fiyatı " + productModel.PriceWithTax.ToString("###,###,##0.00") + " " + productModel.Currency + (string.IsNullOrEmpty(pm.Description) ? "" : ";" + pm.Description);
                    //    ViewData["Description"] = ViewBag.Description;
                    //}
                }
            }

            if (productModel.ProductTabsWithNewTab == null) { productModel.ProductTabsWithNewTab = new List<ProductTab>(); }
            if (productModel.ProductTabsWithoutNewTab == null) { productModel.ProductTabsWithoutNewTab = new List<ProductTab>(); }

            if (string.IsNullOrEmpty(productModel.BreadCrumb) && CategoryId.HasValue && CategoryId > 0)
            {
                productModel.BreadCrumb = dbCategory.GetBreadCrumb((int)CategoryId, Parameters.MainCategoryId, Parameters.HomePageCategoryId, eStoreUser.CultureInfo);
            }
            if (productModel.Description == null)
            {
                productModel.Description = "";
            }
            return PartialView(productModel);
        }

        #endregion

        #region QuickView

        public ActionResult QuickView()
        {
            return View();
        }

        #endregion

        #endregion

        #region ProductPrices

        public ActionResult ProductPrices(int id, string pRelPos)
        {
            ViewBag.SelectedProductId = id;
            ViewBag.productRelatedsPosition = pRelPos;
            ProductModel productModel = new ProductModel();
            Product p = dbProduct.Get(id, eStoreUser.AccountId);
            if (p != null)
            {
                Mapper.MapDomainToViewModel(p, productModel);
            }
            return View(productModel);
        }

        #endregion

        #region ProductDiscount

        public ActionResult ProductDiscount(int id)
        {
            ViewBag.SelectedProductId = id;
            ProductModel productModel = new ProductModel();
            Product p = dbProduct.Get(id, eStoreUser.AccountId);
            if (p != null)
            {
                Mapper.MapDomainToViewModel(p, productModel);
            }
            return View(productModel);
        }

        #endregion

        #region ProductAddToCart

        public ActionResult ProductAddToCart(int id, int? selectedVariant = 0, string pRelPos = "")
        {
            ViewBag.SelectedProductId = id;
            ViewBag.productRelatedsPosition = pRelPos;
            ProductModel productModel = new ProductModel();
            Product p = dbProduct.Get(id, eStoreUser.AccountId);
            if (p != null)
            {
                Mapper.MapDomainToViewModel(p, productModel);
            }

            productModel.variantUrlsList = dbProduct.GetVariantUrls((int)id);
            productModel.variantPropertiesList = dbProduct.GetVariantCombo(p.UstUrunId > 0 ? p.UstUrunId : p.ProductId);
            ViewBag.SelectedVariant = ((int)selectedVariant == 0 && productModel.variantPropertiesList.Count() > 0) ? productModel.variantPropertiesList.FirstOrDefault().id : (int)selectedVariant;

            productModel.BasketLocked = eStoreUser.BasketLocked;
            return View(productModel);
        }

        #endregion

        #region ProductInstallmentsTable

        public ActionResult ProductInstallmentsTable(int id, string PosVoucher = "P")
        {
            ViewBag.SelectedProductId = id;
            ViewBag.PosVoucher = PosVoucher;
            ProductModel productModel = new ProductModel();
            Product p = dbProduct.Get(id, eStoreUser.AccountId);
            if (p != null)
            {
                Mapper.MapDomainToViewModel(p, productModel);
            }
            return View(productModel);
        }

        #endregion

        #region ProductDescription

        public ActionResult ProductDescription(int id)
        {
            ProductModel p = new ProductModel();
            p.Description = dbProduct.GetDescription(id);
            p.Description = p.Description.Replace("{ImageUrl}", Parameters.WebSiteImageUrl).Replace("\r", "").Replace("\n", "").Replace("\t", "");
            p.Information = dbProductInfo.GetListHtml((int)id).Replace("|||", ", ");
            return View(p);
        }

        #endregion

    }
}